package docker_agent

import (
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	"context"
	"fmt"
	"github.com/docker/docker/client"
	"os"
	"path/filepath"
	"strings"
)

func CreateDockerClient(ctx *context.Context) (*client.Client, error) {
	log.Info("检查 Docker 环境")
	// 1. 检查 Docker 环境
	dockerSocketPath, err := GetDockerSocketPath()
	if err != nil {
		return nil, err
	}
	log.Info("dockerSocketPath: %s", dockerSocketPath)
	cli, err := CheckIfDockerRunning(*ctx, dockerSocketPath)
	if err != nil {
		return nil, err
	}
	return cli, nil
}

/*
Docker环境路径优先级: 配置文件、环境变量
*/
func GetDockerSocketPath() (string, error) {
	if setting.Devstar.Devcontainer.DockerHost != "" {
		return setting.Devstar.Devcontainer.DockerHost, nil
	}
	socket, found := os.LookupEnv("DOCKER_HOST")
	if found {
		return socket, nil
	}
	for _, p := range commonSocketPaths {
		if _, err := os.Lstat(os.ExpandEnv(p)); err == nil {
			if strings.HasPrefix(p, `\\.\`) {
				return "npipe://" + filepath.ToSlash(os.ExpandEnv(p)), nil
			}
			return "unix://" + filepath.ToSlash(os.ExpandEnv(p)), nil
		}
	}
	return "", fmt.Errorf("daemon Docker Engine socket not found and docker_host config was invalid")
}
func CheckIfDockerRunning(ctx context.Context, configDockerHost string) (*client.Client, error) {
	opts := []client.Opt{
		client.FromEnv,
	}

	if configDockerHost != "" {
		opts = append(opts, client.WithHost(configDockerHost))
	}

	cli, err := client.NewClientWithOpts(opts...)
	if err != nil {
		return nil, err
	}
	_, err = cli.Ping(ctx)
	if err != nil {
		return nil, fmt.Errorf("cannot ping the docker daemon, is it running? %w", err)
	}
	return cli, nil
}
